package com.demo.connectdbtest.report;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Slf4j
public class ReportPdfController {

    /**
     * test success
     * @param args
     * @throws DocumentException
     */
    public static void main(String[] args) throws DocumentException {
        ArrayList<PdfContentItem> contentItems = new ArrayList<>();

        for (int i = 0; i < 8; i++) {
            PdfContentItem contentItem = new PdfContentItem();
            contentItem.setPickupDate("ZN0335233");
            contentItem.setProductSpecs("pcv");
            contentItem.setWeight("100000");
            contentItem.setTaxedStatementsPrice("22");
            List<String> integers = Arrays.asList("A", "B", "C", "D", "E", "F");
            List<String> type = Arrays.asList("APC", "BPC", "CPC", "DPC", "EPC", "FPC");
            contentItem.setSumTaxedStatementsPrice(integers);
            contentItem.setSecondMergeDataList(type);
            contentItems.add(contentItem);
        }


        JSONObject data = new JSONObject();
        data.put("centerStatementsItemVOS", contentItems);
        data.put("totalScore", 1895);
        data.put("totalAmount", 998);

        //设置表头
        List<String> headList = new ArrayList<>();
        headList.add("设备编号");
        headList.add("兑换类型(PCV/SBPC)");
        headList.add("兑换类型(PCV/SBPC)");
        headList.add("兑换数量");
        headList.add("兑换总积分");
        headList.add("筹码类型");


        //表格中每一列的属性名
        List<String> contentList = new ArrayList<>();
        contentList.add("pickupDate");
        contentList.add("productSpecs");
        contentList.add("weight");
        contentList.add("taxedStatementsPrice");
        contentList.add("sumTaxedStatementsPrice");
        contentList.add("secondMergeDataList");


        //指定列宽度
        ArrayList<Integer> columnWidthList = new ArrayList<>();

        columnWidthList.add(35);
        columnWidthList.add(30);
        columnWidthList.add(30);
        columnWidthList.add(30);
        columnWidthList.add(40);
        columnWidthList.add(40);

        generatePdf("C:\\Users\\braver\\Desktop\\draft", "C:\\Users\\braver\\Desktop\\draft\\test189.pdf",
                "测试excel类型的pdf", "", data, headList, contentList, columnWidthList, PageSize.A3, 8,5);
    }

    /**
     * 生成结算单pdf
     *
     * @param folderName      生成文件的文件夹名称
     * @param fileName        生成文件的全路径文件名
     * @param titleName       文件内容标题
     * @param contentName     文件内容 传递一个JSONObeject对象,将导出的集合list数据放入key=centerStatementsItemVOS的value中
     * @param data            文件表格数据
     * @param headList        表头，每一列的表头名称
     * @param columnWidthList 表头的每一列宽度，如果不指定则根据表头的列数平均计算每一列的宽度
     * @param pageLayout      页面纸张的布局大小，为null则默认A4
     * @param fontSize        页面字体大小，为null则默认10
     *                        contentList：每一列的属性名
     *                        startMergeColumnNum：从第几行开始合并
     * @return
     */
    public static File generatePdf(String folderName, String fileName, String titleName, String contentName, JSONObject data, List<String> headList, List<String> contentList, List<Integer> columnWidthList, Rectangle pageLayout, Integer fontSize,Integer startMergeColumnNum) throws DocumentException {
        try {
            //页面大小
            Rectangle layout = PageSize.A4;
            if (Objects.nonNull(pageLayout)) {
                layout = pageLayout;
            }
            Rectangle rect = new Rectangle(layout);
            //创建文档对象
//            Document document = new Document(rect, 60, 60, 30, 30);
            Document document = new Document(rect, 8, 8, 30, 30);
            File folderFile = new File(folderName);
            if (!folderFile.exists()) {
                log.info("准备创建文件夹. ");
                folderFile.mkdirs();// 如果不存在，创建目录
                log.info("成功创建文件夹. ");
            }
            //设置输出流
            PdfWriter.getInstance(document, new FileOutputStream(fileName));

            document.open();

            // 本地调试用这个字体
            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

            Font fontTitle = new Font(bfChinese, 18, Font.BOLD, BaseColor.BLACK);
            //字体
//            Font fontContent = new Font(bfChinese, 10, Font.NORMAL, BaseColor.BLACK);
            Integer size = 10;
            if (Objects.nonNull(fontSize) && fontSize > 0) {
                size = fontSize;
            }
            Font fontContent = new Font(bfChinese, size, Font.NORMAL, BaseColor.BLACK);

            Paragraph title = new Paragraph(titleName, fontTitle);
            //居中
            title.setAlignment(1);
            document.add(title);

            // 空一行
            Paragraph emptyRow = new Paragraph(10f, " ", fontContent);
            document.add(emptyRow);

            Paragraph content = new Paragraph(contentName, fontContent);
            document.add(content);

            // 空一行
            document.add(emptyRow);

            int columnNum = headList.size();
            PdfPTable headerTable = new PdfPTable(columnNum);
            headerTable.setWidthPercentage(100);
            if (CollectionUtils.isEmpty(columnWidthList)) {
                //没有指定每一列的宽度则平均分配宽度
                Integer columnWidth = 100 / columnNum;
                List<Integer> headerWidthList = new ArrayList<>();
                for (int i = 0; i < columnNum; i++) {
                    headerWidthList.add(columnWidth);
                }
                int[] headerwidths = headerWidthList.stream().mapToInt(Integer::intValue).toArray();
                //int headerwidths[] = {20, 20, 20, 20, 20};
                headerTable.setWidths(headerwidths);
            } else {
                int[] headerwidths = columnWidthList.stream().mapToInt(Integer::intValue).toArray();
                headerTable.setWidths(headerwidths);
            }

            for (int i = 0; i < headList.size(); i++) {
                createTableCell(headList.get(i), fontContent, headerTable);
            }

            JSONArray centerStatementsItemVOS = data.getJSONArray("centerStatementsItemVOS");

            System.out.println(centerStatementsItemVOS);


            // 外层循环构建行，内层循环构建列
            for (int i = 0; i < centerStatementsItemVOS.size(); i++) {
                createTableCellDemo(i, centerStatementsItemVOS, contentList, fontContent, headerTable,startMergeColumnNum);

                for (int j = 0; j < contentList.size(); j++) {
                    String cellValue = centerStatementsItemVOS.getJSONObject(i).getString(contentList.get(j));
//                    createTableCell(centerStatementsItemVOS.getJSONObject(i).getString(contentList.get(j)), fontContent, headerTable);
                }
            }


          /*  PdfPCell cell = new PdfPCell(new Phrase("test"));

            cell.setFixedHeight(120);
            PdfPCell cell2 = new PdfPCell(new Phrase("test2"));
            cell2.setFixedHeight(120);

            PdfPCell cell3 = new PdfPCell(new Phrase("test3"));
            cell3.setFixedHeight(120);
            PdfPCell cell4 = new PdfPCell(new Phrase("test4"));
            cell4.setFixedHeight(120);



            // create a table to fill cell 1
            PdfPTable iTable = new PdfPTable( 1 );
            iTable.setWidthPercentage(100);
            PdfPCell iCell;
             float lineHeight2 = ( float ) 20.0 ;
            iCell = new PdfPCell(new Paragraph( "A" ));
            iCell.setHorizontalAlignment(Element.ALIGN_CENTER);
            iCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            iCell.setFixedHeight(lineHeight2);
            iTable.addCell(iCell);
            iCell = new PdfPCell( new Paragraph( "B" ));
            iCell.setHorizontalAlignment(Element.ALIGN_CENTER);
            iCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            iCell.setFixedHeight(lineHeight2);
            iTable.addCell(iCell);
            iCell = new PdfPCell(new Paragraph( "C" ));
            iCell.setHorizontalAlignment(Element.ALIGN_CENTER);
            iCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            iCell.setFixedHeight(lineHeight2);
            iTable.addCell(iCell);

            iCell = new PdfPCell(new Paragraph( "D" ));
            iCell.setHorizontalAlignment(Element.ALIGN_CENTER);
            iCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            iCell.setFixedHeight(lineHeight2);
            iTable.addCell(iCell);

            iCell = new PdfPCell(new Paragraph( "E" ));
            iCell.setHorizontalAlignment(Element.ALIGN_CENTER);
            iCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            iCell.setFixedHeight(lineHeight2);
            iTable.addCell(iCell);

            iCell = new PdfPCell(new Paragraph( "F" ));
            iCell.setHorizontalAlignment(Element.ALIGN_CENTER);
            iCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            iCell.setFixedHeight(lineHeight2);
            iTable.addCell(iCell);

            PdfPCell cell5 = new PdfPCell(iTable);
            cell5.setPadding(0);




            headerTable.addCell(cell);
            headerTable.addCell(cell2);
            headerTable.addCell(cell3);
            headerTable.addCell(cell4);
            headerTable.addCell(cell5);
*/


            // 构建表格尾（根据需求修改，也可作为入参传进来）

            document.add(headerTable);
            // 文件末尾添加字段说明
            document.add(new Paragraph("合计:1500.00", fontContent));
            document.close();
            File file = new File(fileName);
            return file;
        } catch (DocumentException e) {
            throw new RuntimeException(e);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @param row                     每一行数据的索引
     * @param centerStatementsItemVOS
     * @param contentList             表头对应列的属性名
     * @param fontContent
     * @param headerTable
     * @param headerTable
     * @param startMergeColumnNum 从第几行开始合并
     */
    private static void createTableCellDemo(int row, JSONArray centerStatementsItemVOS, List<String> contentList, Font fontContent, PdfPTable headerTable,Integer startMergeColumnNum) {
        //每一行数据对象
        JSONObject jsonObject = centerStatementsItemVOS.getJSONObject(row);
        //        String cellValue = centerStatementsItemVOS.getJSONObject(row).getString(contentList.get(column));
        float lineHeight2 = (float) 20.0;

        //构建每一行
        //5列数据 暂时假定五列数据
        ArrayList<PdfPCell> pdfList = new ArrayList<>();

        for (int i = 0; i < contentList.size(); i++) {
            //从第几项开始就是嵌套一个表格的
            if (i >= (startMergeColumnNum - 1)) {
                List array = jsonObject.getObject(contentList.get(i), List.class);


                PdfPTable iTable = new PdfPTable(1);
                //PdfPCell cell5 = null;
                PdfPCell cell5 = new PdfPCell(iTable);


                for (int j = 0; j < array.size(); j++) {
                    iTable.setWidthPercentage(100);
                    PdfPCell iCell;
                    iCell = new PdfPCell(new Paragraph("" + array.get(j)));
                    iCell.setHorizontalAlignment(Element.ALIGN_CENTER);
                    iCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                    iCell.setFixedHeight(lineHeight2);
                    iTable.addCell(iCell);
                }
                //                cell5 = new PdfPCell(iTable);
                cell5.setPadding(0);
                pdfList.add(cell5);

            } else {
                String cellValue = jsonObject.getString(contentList.get(i));
                PdfPCell cell = new PdfPCell(new Phrase(cellValue));
                cell.setFixedHeight(120);
                // 设置单元格的垂直对齐方式 ： 居中
                cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                // 设置单元格的水平对齐方式 ：居中对齐
                //cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                pdfList.add(cell);

            }


        }

        if (!CollectionUtils.isEmpty(pdfList)) {
            for (PdfPCell pdfPCell : pdfList) {
                headerTable.addCell(pdfPCell);
            }
        }


/*  PdfPCell cell = new PdfPCell(new Phrase("test"));

            cell.setFixedHeight(120);
            PdfPCell cell2 = new PdfPCell(new Phrase("test2"));
            cell2.setFixedHeight(120);

            PdfPCell cell3 = new PdfPCell(new Phrase("test3"));
            cell3.setFixedHeight(120);
            PdfPCell cell4 = new PdfPCell(new Phrase("test4"));
            cell4.setFixedHeight(120);



            // create a table to fill cell 1
            PdfPTable iTable = new PdfPTable( 1 );
            iTable.setWidthPercentage(100);
            PdfPCell iCell;
             float lineHeight2 = ( float ) 20.0 ;
            iCell = new PdfPCell(new Paragraph( "A" ));
            iCell.setHorizontalAlignment(Element.ALIGN_CENTER);
            iCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            iCell.setFixedHeight(lineHeight2);
            iTable.addCell(iCell);
            iCell = new PdfPCell( new Paragraph( "B" ));
            iCell.setHorizontalAlignment(Element.ALIGN_CENTER);
            iCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            iCell.setFixedHeight(lineHeight2);
            iTable.addCell(iCell);
            iCell = new PdfPCell(new Paragraph( "C" ));
            iCell.setHorizontalAlignment(Element.ALIGN_CENTER);
            iCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            iCell.setFixedHeight(lineHeight2);
            iTable.addCell(iCell);

            iCell = new PdfPCell(new Paragraph( "D" ));
            iCell.setHorizontalAlignment(Element.ALIGN_CENTER);
            iCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            iCell.setFixedHeight(lineHeight2);
            iTable.addCell(iCell);

            iCell = new PdfPCell(new Paragraph( "E" ));
            iCell.setHorizontalAlignment(Element.ALIGN_CENTER);
            iCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            iCell.setFixedHeight(lineHeight2);
            iTable.addCell(iCell);

            iCell = new PdfPCell(new Paragraph( "F" ));
            iCell.setHorizontalAlignment(Element.ALIGN_CENTER);
            iCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
            iCell.setFixedHeight(lineHeight2);
            iTable.addCell(iCell);

            PdfPCell cell5 = new PdfPCell(iTable);
            cell5.setPadding(0);

            headerTable.addCell(cell);
            headerTable.addCell(cell2);
            headerTable.addCell(cell3);
            headerTable.addCell(cell4);
            headerTable.addCell(cell5);
*/

    }

    /**
     * 创建表格单元格
     *
     * @param content     内容
     * @param fontContent 字体
     * @param headerTable 表格对象
     */
    private static void createTableCell(String content, Font fontContent, PdfPTable headerTable) {
        Phrase phrase = new Phrase(content, fontContent);
        phrase.add(Chunk.NEWLINE);
        PdfPCell pdfPCell = new PdfPCell(phrase);
        pdfPCell.setFixedHeight(18);
        pdfPCell.setHorizontalAlignment(1);
        pdfPCell.setVerticalAlignment(1);
        pdfPCell.setNoWrap(false);
        headerTable.addCell(pdfPCell);
    }

}
